from flask import Flask, render_template, request, make_response
from json import JSONEncoder
from io import BytesIO
import ds_drawer
import mimetypes
app = Flask("SAMDrawer")


@app.context_processor
def consts():
    return {
        "USING_SSL": False
    }


@app.route("/", methods=["GET"])
def root():
    return render_template("main.html")


@app.route("/draw", methods=["POST", "GET"])
def draw():
    datas = None
    if request.method == "GET":
        datas = request.args
    else:
        datas = request.form
    if "string" not in datas:
        return encode_json({
            "code": -1,
            "message": "Please give a string."
        })
    string = datas["string"]
    if len(string) > 50:
        return encode_json({
            "code": -1,
            "message": "Too long.."
        })
    svg_data = ""
    target = ds_drawer.generate_graph(string, "svg")
    with open(target, "r") as file:
        svg_data = file.read()

    return encode_json({
        "code": 0,
        "data": svg_data
    })


def encode_json(obj):
    return JSONEncoder().encode(obj)


if __name__ == "__main__":
    app.run(host="127.0.0.1", port="90")
